﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Connectivity;

namespace SpaceNeedle.x6473.WindowsPhone.Common
{
    public class NetworkService : NetworkServiceBase
    {
        public NetworkService ()
	    {
            NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
            this.HandleState();
	    }

        void NetworkInformation_NetworkStatusChanged(object sender)
        {
            this.HandleState();
        }

        public override void HandleState()
        {
            if (isVerifyingConnection)
            {
                return;
            }

            isVerifyingConnection = true;

            try
            {
                ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

                    if (InternetConnectionProfile == null)
                    {
                        this.IsConnected = false;

                        if (this.isConnected)
                        {
                            this.isConnected = false;
                            this.OnDisconnected();
                        }
                    }
                    else
                    {
                        if (InternetConnectionProfile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.InternetAccess)
                        {
                            this.IsConnected = false;

                            if (this.isConnected)
                            {
                                this.isConnected = false;
                                this.OnDisconnected();
                            }
                        }
                        else
                        {
                            this.IsConnected = true;

                            if (!this.isConnected)
                            {
                                this.isConnected = true;
                                if (this.wasConnectedOnceBefore)
                                {
                                    this.OnReconnected();
                                }

                                this.OnConnected();
                                this.wasConnectedOnceBefore = true;
                            }
                        }
                    }
            }
            catch
            {
            }

            isVerifyingConnection = false;
        }
    }
}
